import React, {useCallback} from "react";

import Qmap, {queryAddress, queryLocation} from 'react-qqmap';
import {LdhButton, LdhInput, Message} from "./Components";
import {Col, Row} from "antd";

const KEY = "GQIBZ-5ZFWV-ZPLPQ-5X7FZ-P67I6-2PFOB";
const DEFAULT_CENTER = {lng: 120.129295, lat: 30.301348}

export default class LdhMap extends React.Component {

    constructor(props) {
        super(props);
        let {originPos} = props;
        this.state = {
            keyword: "",
            pos: originPos||{},
            options: {center:originPos}
        }
    }



    getLatLng(location) {
        const LatLng = new this.TMap.LatLng(
            location?.lat || 39.908802,
            location?.lng || 116.397502,
        );
        return LatLng;
    }

    addMarker(title, location) {
        const position = this.getLatLng(location);
        this.instance.setCenter(position);
        this.marker.add([
            {id: title, styleId: 'marker', position},
        ]);
    }

    removeMarker(title) {
        this.marker.remove([title]);
    }

    handleKeywordChange(e) {
        this.setState({keyword: e.target.value});
    }

    handleSearch() {
        let {keyword} = this.state;
        // 根据地址查询对应的经纬度，并打上标记
        queryLocation({key: KEY,address:keyword,}).then((res) => {
            if(res.status!=0){
                Message.warning(res.message);
                return;
            }
            let {result:{address_components, location}} = res;
            let {province, city, district} = address_components;
            Message.info(`${province} ${city} ${district}`);

            this.handleClick(location);

        });
    }
    handlePosChange(pos){
        this.setState({pos})
        let {onPosChange} = this.props;
        onPosChange && onPosChange(pos);
    }

    // 点击定位
    handleClick(latLng){
        this.removeMarker("POS");
        this.addMarker("POS", latLng)
        this.setState({options:{center:latLng}})


        this.infoWindow.close();
        this.infoWindow.setPosition(latLng);
        queryAddress({key: KEY, location: latLng}).then(res => {
            let {formatted_addresses, address_component} = res.result;
            let name = formatted_addresses.recommend;

            let {province, city, district, street} = address_component
            let {lat, lng} = latLng;
            let address = `${province} ${city} ${district} ${street}`;
            let pos = {lat, lng, province, city, district, street, address};
            this.handlePosChange(pos);
            this.infoWindow.setContent(`<b>${name}</b><div>${address}</div><div style="font-size: 12px; color: #999">${lat} / ${lng}</div>`)
            this.infoWindow.open();
        });
    }

    render() {
        let {keyword, pos, options} = this.state;
        let {...rest} = this.props;
        return <div>
            <Row className="mb-5">
                <Col span={20}>
                    <LdhInput value={keyword} onChange={this.handleKeywordChange.bind(this)}/>

                </Col>
                <Col span={4}>
                    <LdhButton onClick={this.handleSearch.bind(this)} type="primary" className="h-40">查询</LdhButton>
                </Col>
            </Row>
            <div className="flex-between">
                <div>地址：<b>{pos.address}</b></div>
                <div>纬度：<b>{pos.lat}</b> 经度：<b>{pos.lng}</b></div>
            </div>
            <Qmap id="container" API_GL_KEY={KEY} options={options} {...rest}
                  onInit={({constructor, instance, marker}) => {
                      this.TMap = constructor;
                      this.instance = instance;
                      this.marker = marker;
                      let c = DEFAULT_CENTER;//options.center;
                      let center = new constructor.LatLng(c.lat, c.lng);
                      this.infoWindow = new constructor.InfoWindow({
                          map: instance,
                          position: center, //设置信息框位置
                          content: 'Hello World!', //设置信息框内容

                      });
                      instance.on("click", (e) => {
                          this.handleClick(e.latLng);
                      })
                        let {originPos} = this.props;
                      this.handleClick(this.getLatLng(originPos));

                  }}>

            </Qmap>
        </div>
    }

}